package com.summer.utils.file.impl;

import com.summer.utils.file.CutFileService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;

public class CutFileServiceImpl implements CutFileService {

    private static final Log logger = LogFactory.getLog(CutFileServiceImpl.class);

    /**
     * 按行分割文件
     * @param rows 为多少行一个文件
     * @param sourceFilePath 为源文件路径
     * @param targetDirectoryPath 文件分割后存放的目标目录
     */
    @Override
    public void splitDataToSaveFile(int rows, String sourceFilePath, String targetDirectoryPath) {

        File sourceFile = new File(sourceFilePath);
        File targetFile = new File(targetDirectoryPath);
        if (!sourceFile.exists() || rows <= 0 || sourceFile.isDirectory()) {
            return;
        }
        if (targetFile.exists()) {
            if (!targetFile.isDirectory()) {
                return;
            }
        } else {
            targetFile.mkdirs();
        }
        try {

            InputStreamReader in = new InputStreamReader(new FileInputStream(sourceFilePath), "UTF-8");
            BufferedReader br = new BufferedReader(in);

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                    targetFile.getAbsolutePath() + "/" + sourceFile.getName() + "_1.txt",true), "UTF-8"), 1024);

            StringBuffer str = new StringBuffer();
            String tempData = br.readLine();
            // i 记录当前读取的是第几行数据  j负责buffer池里面读取的是第几行数据，s 记录的是第几个文件
            int i = 1, s = 1,j=1;
            while (tempData != null) {
                str.append(tempData).append("\r\n");
                if(j%1000==0){
                    bw.write(str.toString());
                    str = new StringBuffer();
                    j=1;
                }

                if (i % rows == 0) {
                    if(str!=null&&str.toString().length()>0){
                        bw.write(str.toString());
                        str = new StringBuffer();
                        j=1;
                    }
                    bw.close();
                    bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
                            targetFile.getAbsolutePath() + "/" + sourceFile.getName() + "_" + (s + 1) + ".txt",true), "UTF-8"), 1024);

                    s += 1;
                }
                i++;
                j++;
                tempData = br.readLine();
            }

            bw.write(str.toString());
            bw.close();
            br.close();
            in.close();

        } catch (Exception e) {
            logger.info("mf split file is error ",e);
            throw new RuntimeException("切包失败,e="+e.getMessage());
        }
    }
}
